extends Piece

@export var CostLabel: Label
@export var HPLabel: Label
@export var PlayerCard: ColorRect
@export var HighLight: Sprite2D
@export var HighLight2: NinePatchRect
@export var DeckBasePoint: Node2D
@export var Deck:Path2D

var left_cost = 3
var max_cost = 3

var speed = 2.0

var draw_number_each_turn = 5

func _ready():
	is_block = true
	camp = CAMP.PLAYER
	can_move = true
	max_hp = 50
	left_hp = 50
	# 设置角色卡的位置，依次往下排
	PlayerCard.position += Vector2(0, 180) * len(Chessboard.player_list)
	# 让高亮不可见
	HighLight.visible = false
	HighLight2.visible = false
	# 刷新角色卡上的数字
	update_label()

# 计算移动需要的费用
func calculate_move_cost(target_coord):
	var distance = abs(my_coord[0] - target_coord[0]) + abs(my_coord[1] - target_coord[1])
	return distance / speed

# 角色移动时，要考虑4个要素：
# 1. 改变Cost
# 2. 改变Position
# 3. 改变自己记录的coord
# 4. 改变Chessboard array

# 尝试移动，需要检查费用以及目标位置是否可用，
# 同时更新自己的cost, 自己的position, 自己的coord, 棋盘array
func try_move_player(target_coord):
	var need_cost = calculate_move_cost(target_coord)
	if have_enough_cost(need_cost) and Chessboard.can_move_array(target_coord):
		update_cost(left_cost - need_cost)
		# Chessboard.move_array(self, my_coord, target_coord)
		move(target_coord)

# 更新费用的通用方法
# 所有更新角色费用的操作都要通过这个方法，为了确保UI组件也被更新
func update_cost(cost):
	left_cost = cost
	update_label()

# 判断费用是否足够的方法
func have_enough_cost(need_cost):
	if need_cost > left_cost:
		print("no enough cost")
		return false
	return true

# 更新角色卡上的数字，费用和HP
func update_label():
	CostLabel.text = "Cost: " + str(left_cost) + "/" + str(max_cost)
	HPLabel.text = "HP: " + str(left_hp) + "/" + str(max_hp)

# 被选中时
func get_focus():
	if Chessboard.board_state == Chessboard.STATE.IDLE or Chessboard.board_state == Chessboard.STATE.PLAYER_MOVE:
		Chessboard.board_state = Chessboard.STATE.PLAYER_MOVE
		#检查现在是否有别的player被选中，有的话要先让那个player的高亮去掉
		if Chessboard.focus_player != null:
			Chessboard.focus_player.remove_focus()
		Chessboard.focus_player = self
		# 设置自己的高亮启动
		HighLight.visible = true
		HighLight2.visible = true
		get_parent().move_child(self, 1)
		z_index = 4
		DeckBasePoint.get_focus()

# 不再被选中时
func remove_focus():
	# 不再被选中时，把高亮关掉
	if Chessboard.focus_player == self:
		Chessboard.focus_player = null
	HighLight.visible = false
	HighLight2.visible = false
	get_parent().move_child(self, 0)
	z_index = 2
	DeckBasePoint.remove_focus()

# 回合开始时的行为
func on_turn_start():
	update_cost(max_cost)
	Deck.draw_card(5)
	print("player turn start")


# 受到伤害
# TODO 追加伤害修正值的逻辑 
func receive_dmg(value_in):
	left_hp -= value_in
	update_label()
